package com.ddpt.permission.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lh.center.common.base.ResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 熔断、限流等状态统一拦截处理
 */
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletRequest.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=utf-8");
        AbstractRule rule = e.getRule();
        ResponseEntity<String> entity = ResponseEntity.error("网络繁忙，请稍后再试");
        if(rule instanceof FlowRule){
            String refResource = ((FlowRule) rule).getRefResource();
            if(StringUtils.isNotBlank(refResource)){
                entity = ResponseEntity.error(refResource);
            }
        }
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), entity);
    }
}
